const axios = require('axios');
class DouyinParser {
  async parse(url, timeout) {
    try {
      const response = await axios.get(url, {
        timeout,
        headers: {
          'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15'
        }
      });

      const html = response.data;
      // 抖音特定解析逻辑
      const regex = /window\._ROUTER_DATA\s*=\s*(.*?)<\/script>/s;
      const match = html.match(regex);

      if (!match || !match[1]) {
        console.log("No _ROUTER_DATA found in HTML");
        return {
          code: 201,
          msg: "解析失败：未能从页面获取视频数据，可能是页面结构变化、接口受限或视频已被删除",
        };
      }

      const videoInfo = JSON.parse(match[1].trim());
      if (!videoInfo.loaderData) {
        return {
          code: 201,
          msg: "解析失败：视频数据结构异常，可能是抖音接口发生变化",
        };
      }

      try {
        const videoData = videoInfo.loaderData["video_(id)/page"]?.videoInfoRes?.item_list?.[0];
        // 检查必要字段是否存在
        if (!videoData.author) {
          return {
            code: 201,
            msg: "解析失败：视频作者信息缺失",
          };
        }

        if (!videoData.video?.play_addr?.url_list?.[0]) {
          return {
            code: 201,
            msg: "解析失败：视频播放地址缺失",
          };
        }

        const videoResUrl = videoData.video.play_addr.url_list[0].replace(
          "playwm",
          "play"
        );
        return {
          code: 200,
          msg: "解析成功",
          data: {
            author: videoData.author.nickname || "未知作者",
            uid: videoData.author.unique_id || "",
            avatar: videoData.author.avatar_medium?.url_list?.[0] || "",
            like: videoData.statistics?.digg_count || 0,
            time: videoData.create_time || 0,
            title: videoData.desc || "无标题",
            cover: videoData.video.cover?.url_list?.[0] || "",
            url: videoResUrl,
            music: {
              author: videoData.music?.author || "未知音乐作者",
              avatar: videoData.music?.cover_large?.url_list?.[0] || "",
            },
          },
        };
      } catch (error) {
        console.error("Error parsing video data:", error);
        return { code: 500, msg: `服务器错误：${error.message || "未知错误"}` };
      }


    } catch (error) {
      throw new Error(`抖音解析失败: ${error.message}`);
    }
  }
}

module.exports = DouyinParser;